package com.heima.tradeservice.listener;

import com.heima.api.client.PayClient;
import com.heima.api.domain.dto.PayOrderDTO;
import com.heima.tradeservice.constants.MqConstants;
import com.heima.tradeservice.domain.po.Order;
import com.heima.tradeservice.service.IOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class DelayMessageListener {
    private final IOrderService orderService;
    private final PayClient payClient;
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstants.DELAY_ORDER_QUEUE_NAME,durable = "true"),
            exchange = @Exchange(name = MqConstants.DELAY_EXCHANGE_NAME,delayed = "true"),
            key = MqConstants.DELAY_ORDER_ROUTING_KEY
    ))
    public void listenerDelayMessage(Long orderId){

//        1.查询订单
        Order order = orderService.getById(orderId);
//        2.检测订单状态，判断是否已经支付
        if (order == null || order.getStatus() != 1){
            return;
        }
//        3.未支付，需要查询支付流水状态
        PayOrderDTO payOrderDTO = payClient.queryByBizOrderNo(orderId);
//        4.判断支付流水状态，是否支付成功
        if (payOrderDTO != null && payOrderDTO.getStatus() == 3){
//            4.1.支付成功
            orderService.markOrderPaySuccess(orderId);
        } else {
//            4.2.未支付，取消订单
            orderService.cancelOrder(orderId);
            System.out.println(orderId);
            System.out.println("订单已取消");
        }

    }
}
